import GameConfig from "./GameConfig";

cc.Class({
    extends: cc.Component,

    properties: {
        initPosY: 0,
        flyAudio: {
            type: cc.AudioClip,
            default: null,
        },
        // 跟随的防护球
        defensePic: cc.Prefab,
    },

    onLoad () {
        this.posX = -265;

        this.defenseItem = cc.instantiate(this.defensePic);
        this.defenseItem.opacity = 0;
        this.node.addChild(this.defenseItem);
        this.defenseItem.setPosition(cc.v2(0, 0));

        // 触摸
        var touchReceiver = cc.Canvas.instance.node;
        touchReceiver.on('touchstart', this._onTouchStart, this);

        // 序列帧动画
        this.anim = this.getComponent(cc.Animation);
        this.sequentialFrameAnimation = {
            "runLeft": {name: "runLeft", speed: 3},
            "runRight": {name: "runRight", speed: 3},
            "jump": {name: "jump", speed: 5},
            "jumpBack": {name: "jumpBack", speed: 5},
        }; 
        // 动画帧准备
        this.jumpPlayerWidthRate = 1;
        this._prepareAnim();
    },

    start () {
        this.posY = this.initPosY;
        // 是否可点击
        this.touchEnable = false;
        // 是否攻击状态
        this.isInvasive = false; 
        // 计时器初始化
        this.timer = 0;
        // 产生障碍/防护球/加分道具的距离记录
        this.distance4Barrier = 0;
        this.distance4Defense = 0;
        this.distance4ScoreProps = 0;
        this.distance4Rotation = 0;
        // 0-普通状态 1-无敌状态
        this.status = 0; 
    },

    init(game, playerName) {
        this.game = game;
        this.playerName = playerName;
    },

    _prepareAnim() {
        var _self = this;
        cc.loader.loadRes(_self.playerName + "/run_right", cc.SpriteAtlas, function (err, atlas) {
            _self.sequentialFrameAnimation["runRight"].frames = atlas.getSpriteFrames();
            _self.initRightSprite = _self.sequentialFrameAnimation["runRight"].frames[0];
            _self._prepareRunAnimation("runRight");
        });
        cc.loader.loadRes(_self.playerName + "/run_left", cc.SpriteAtlas, function (err, atlas) {
            _self.sequentialFrameAnimation["runLeft"].frames = atlas.getSpriteFrames();
            _self.initSprite = _self.sequentialFrameAnimation["runLeft"].frames[0];
            _self.getComponent(cc.Sprite).spriteFrame = _self.initSprite;
            _self._prepareRunAnimation("runLeft");
        });
        cc.loader.loadRes(_self.playerName + "/jump", cc.SpriteAtlas, function (err, atlas) {
            _self.sequentialFrameAnimation["jump"].frames = atlas.getSpriteFrames();
            _self._prepareJumpAnimation("jump", false);
            
            _self._jumpCallBack();

            _self.sequentialFrameAnimation["jumpBack"].frames = _self.sequentialFrameAnimation["jump"].frames.reverse();
            _self._prepareJumpAnimation("jumpBack", true);

        });

        // 掉落
        cc.loader.loadRes(_self.playerName + "/fall", cc.SpriteFrame, function (err, spriteFrame) {
            _self.fallSprite = spriteFrame;
        });
    },

    _jumpCallBack() {
        this.jumpAnim = this.anim;
        this.jumpAnim.on('finished', this._jumpFinished, this);
        this.jumpBackAnim = this.anim;
        this.jumpAnim.on('finished', this._jumpFinished, this);
    },

    _prepareRunAnimation(name) {
        var frames = this.sequentialFrameAnimation[name].frames;
        var sprite = this.node.getComponent(cc.Sprite);
        sprite.spriteFrame = frames[0];
        var item = this.sequentialFrameAnimation[name];
        var animation = this.anim;
        var frames = item.frames;
        var clip = cc.AnimationClip.createWithSpriteFrames(frames, frames.length);
        clip.name = name;
        clip.wrapMode = cc.WrapMode.Loop;
        clip.speed = item.speed;
        animation.addClip(clip);
    },

    // 整个动画预定为0.25秒跑完
    _prepareJumpAnimation(name, atRight) {
        var frames = this.sequentialFrameAnimation[name].frames;
        var item = this.sequentialFrameAnimation[name];
        var animation = this.anim;
        var frames = item.frames;
        var clip = cc.AnimationClip.createWithSpriteFrames(frames, frames.length * 4);
        clip.name = name;
        clip.wrapMode = cc.WrapMode.Normal;
        clip.curveData.props = {
            "x": [
                {"frame": 0,    "value": atRight ? 265 : -265},
                {"frame": 0.25, "value": atRight ? -265 : 265}
            ],
        };
        animation.addClip(clip);
    },

    _onTouchStart(event) {
        if (this.touchEnable && GameConfig.GAME_START && !GameConfig.GAME_OVER_LAYER_DISPLAY) {
            this.touchEnable = false;
            this._jumpAnim(); // 跳跃动画
        }
    },

    goRun() {
        var animName = this.node.position.x > 0 ? "runRight" : "runLeft";
        this.anim.play(animName);
    },

    _jumpAnim() {
        this.width = 84;
        this.height = 88;
        this.isInvasive = true;
        var atRight = this.node.position.x > 0;
        this._playFlyAudio();
        if (atRight) {
            this.jumpBackAnim.play("jumpBack");
        } else {
            this.jumpAnim.play("jump");
        }
    },

    _jumpFinished() {
        this.isInvasive = false;
        this.touchEnable = true;
        this.goRun();
    },

    _playFlyAudio() {
        // 调用声音引擎播放声音
        if (null != this.flyAudioId) {
            cc.audioEngine.stop(this.flyAudioId);
        }
        this.flyAudioId = cc.audioEngine.playEffect(this.flyAudio, false);
    },

    _playerMove(x, y) {
        this.node.setPosition(cc.v2(x, y));
    },

    bindDefense(defense) {
        this.defense = defense;
    },

    // 掉落动画
    fallDown() {
        this.anim.stop();
        this.getComponent(cc.Sprite).spriteFrame = this.fallSprite;
        if (this.fallSprite) {
            this.node.width = this._getFrameSize(this.fallSprite).width;
            this.node.height = this._getFrameSize(this.fallSprite).height;
        }

        var jumpDown = cc.moveBy(2, cc.v2(0, -GameConfig.WINDOWS_SIZE.height/2 - 100));
        var callback = cc.callFunc(this._fallFinished, this);
        this.node.runAction(cc.sequence(jumpDown, callback));
    },

    _fallFinished() {
        this.game.overLayer();
    },

    // 复活后npc逻辑
    gameContinue() {
        this.node.opacity = 255;
        if (this.initSprite) {
            this.node.width = this._getFrameSize(this.initSprite).width;
            this.node.height = this._getFrameSize(this.initSprite).height;
        }
        var playerPos = GameConfig.NINJA_POSITION_WHEN_OVER;
        var basePosX = GameConfig.WINDOWS_SIZE.width/2 - 67 - this.node.width/2;
        if (null == playerPos || playerPos.x < 0) {
            basePosX *= -1;
        }
        this.node.setPosition(cc.v2(basePosX, GameConfig.NINJA_STOP_POSY));
        this.posX = basePosX;
        if (playerPos.x > 0) {
           this.getComponent(cc.Sprite).spriteFrame = this.initRightSprite;
        } else {
            this.getComponent(cc.Sprite).spriteFrame = this.initSprite;
        }
    },

    // 获取序列帧的宽高
    _getFrameSize(frame) {
        return {width: frame._originalSize.width, height: frame._originalSize.height};
    },

    // 减少一点护甲
    reduceLifeCount() {
        var nowLifeCount = this.defenseItem.getComponent('FollowDefense').getLifeCount();
        if (nowLifeCount > 0) {
            nowLifeCount--;
            this.defenseItem.getComponent('FollowDefense').updateLifeCount(nowLifeCount);
        }
        if (nowLifeCount <= 0) {
            this.defenseItem.opacity = 0;
            this.status = 0;
        }
    },

    update(dt) {
        if (GameConfig.GAME_READY) {
            // 开场秀
            if (!GameConfig.GAME_START) {
                this.posY += GameConfig.PROPS_PLAYER_MOVE_SPEED;
                this._playerMove(this.posX, this.posY);
                if (this.posY >= GameConfig.NINJA_STOP_POSY) {
                    GameConfig.GAME_START = true;
                    this.touchEnable = true;
                }
            }

            // 获得分数
            this.timer += dt;
            if (this.timer >= GameConfig.GAIN_SCORE_SPEED) {
                this.timer = 0;
                this.game.gainScore();
            }

            if (GameConfig.GAME_START) {
                // 生成障碍判断
                this.distance4Barrier += GameConfig.PROPS_PLAYER_MOVE_SPEED;
                if (this.distance4Barrier >= GameConfig.BARRIER_UNIT_DISTANCE) {
                    this.distance4Barrier = 0;
                    this.game.createBarrier();
                }

                // 生成防护球判断
                this.distance4Defense += GameConfig.PROPS_PLAYER_MOVE_SPEED;
                if (this.distance4Defense >= GameConfig.DEFENSE_UNIT_DISTANCE) {
                    this.distance4Defense = 0;
                    this.game.createDefense();
                }

                // 生成加分道具判断
                this.distance4ScoreProps += GameConfig.PROPS_PLAYER_MOVE_SPEED;
                if (this.distance4ScoreProps >= GameConfig.DEFENSE_UNIT_DISTANCE) {
                    this.distance4ScoreProps = 0;
                    this.game.createScoreProps();
                }

                // 旋转判断
                this.distance4Rotation += GameConfig.PROPS_PLAYER_MOVE_SPEED;
                if (this.distance4Rotation >= GameConfig.ROTATION_UNIT_DISTANCE) {
                    this.distance4Rotation = 0;
                    this.game.rotateIt();
                }
            }
        }
    },
});
